import string
from tools import config
from plugins.linux import uptime
from plugins.linux import loadavg
import logging

logging.basicConfig (level = logging.DEBUG, format = "%(created)-15s %(msecs)d %(levelname)8s %(thread)d %(name)s %(message)s")
log = logging.getLogger (__name__)

peers=[[],[]]

debug = config.getDebug ()

def sendalert(plugin):
	global debug
	if debug :
		log.debug("sendalert")
	global peers
	for peer in peers[1]:
		peer.send_msg ("alert "+plugin+" "+eval(plugin+".get()"))

def parsemsg(msg,client,plugin_and_rb):
	"""Parses the messages, manages the states."""
	global debug
	if debug :
		log.debug ("parsemsg")
	global peers
	data = ""
	m = list (string.split (msg, ' '))
	m1 = m.pop(0)
	known_peer = False
	if client in peers[1] :
		known_peer = True

	if m1=="get" and known_peer:
		if len(m) == 1 and m[0] in config.getAllPlugins() :
			client.send_msg ("reply " + m[0] + " " + eval(m[0] + ".get()") + \
				"\r\n")
#			client.data_out="reply "+m[0]+" "+eval(m[0]+".get()")+"\r\n"
#			client.ready_to_send=True
		elif len(m) == 2 and m[0] in plugin_and_rb[0] :
			idx=plugin_and_rb[0].index(m[0])
			plugin_and_rb[3][idx].acquire ()
			rblist=plugin_and_rb[1][idx].get ()
			plugin_and_rb[3][idx].notifyAll ()
			plugin_and_rb[3][idx].release ()
			idx = 0
			for x in rblist:
				if int (x[0]) > int (m[1]) :
					idx = rblist.index (x)
					break
			data = "reply " +m[0]
			for x in rblist[idx:]:
				data += "|" + str(x[0]) + " " + str(x[1])
			data += "\r\n"
			client.send_msg (data)

	elif m1 == "hi" and len(m)>0 :
		peername = m[0]
		if peername in peers[0] :
			idx = peers[0].index (peername)
		else :
			peers[0].append (peername)
			peers[1].append (client)
			idx = -1
		if idx > -1:
			peers[1][idx] = client;
		client.send_msg ("hi " + config.getNodeID() + "\r\n")

	elif m1 == "re" and len(m)>0 :
		peername = m[0]
		idx = -1
		try:
			idx = peers[0].index (peername)
		except ValueError:
			peers[0].append(peername)
			peers[1].append (client)
		if idx == -1:
			client.send_msg ("hi " + config.getNodeID() + "\r\n")
		else:
			peers[1][idx] = client
			client.send_msg ("re " + config.getNodeID() + "\r\n")


